<template>
  <div class="profile-page">
    <h2 class="page-subtitle">个人信息管理</h2>

    <div class="profile-container">
      <div class="profile-card">
        <div class="loading" v-if="loading">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>

        <div v-else-if="error" class="error-message">
          <div class="error-icon">⚠️</div>
          <p>{{ error }}</p>
          <button @click="fetchUserInfo" class="retry-btn">重试</button>
        </div>

        <ProfileForm
          v-else
          :user-info="userInfo"
          @save-success="handleSaveSuccess"
          @save-error="handleSaveError"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import ProfileForm from './ProfileForm.vue';
import { request } from '@/utils/request.ts';

// 定义用户信息类型
interface UserInfo {
  userId: number;
  username: string;
  phone: string;
  email: string;
  department: string;
  role: string;
  grade: string;
  major: string;
}

interface UserApiResponse {
  userID: number;
  username: string;
  phone: string;
  email: string;
  department: string;
  grade: string;
  major: string;
  createTime: string;
}

interface ApiResponse {
  success: boolean;
  message?: string;
  user?: UserApiResponse;
}

// 状态管理
const loading = ref(true);
const error = ref('');
const userInfo = ref<UserInfo>({
  userId: 0,
  username: '',
  phone: '',
  email: '',
  department: '',
  role: '',
  grade: '',
  major: ''
});

// 获取用户信息
const fetchUserInfo = async (): Promise<void> => {
  try {
    loading.value = true;
    error.value = '';
    const userId = localStorage.getItem('userId');

    if (!userId) {
      error.value = '未获取到用户信息，请重新登录';
      return;
    }

    // 🎯 修复：你的 request 返回的是直接业务数据，不是 AxiosResponse
    const response: ApiResponse = await request.get('/api/user/info', {
      params: {
        userId: parseInt(userId)
      }
    });

    console.log('用户信息响应:', response);

    // 🎯 修复：直接访问 response，不是 response.data
    if (response.success && response.user) {
      const userData = response.user;

      userInfo.value = {
        userId: userData.userID,
        username: userData.username,
        phone: userData.phone || '',
        email: userData.email || '',
        department: userData.department || '',
        role: 'user',
        grade: userData.grade || '',
        major: userData.major || ''
      };

      console.log('映射后的用户信息:', userInfo.value);
      error.value = '';
    } else {
      error.value = response.message || '获取用户信息失败';
    }
  } catch (err) {
    console.error('获取用户信息失败:', err);
    error.value = '网络错误，无法获取用户信息';
  } finally {
    loading.value = false;
  }
};

// 保存成功后重新加载数据
const handleSaveSuccess = (): void => {
  console.log('保存成功，重新加载用户信息...');
  fetchUserInfo();
};

// 处理保存错误
const handleSaveError = (message: string): void => {
  alert(`更新失败：${message}`);
};


// 初始化加载用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>
<style scoped>
.profile-page {
  width: 100%;
  height: 100%;
}

.page-subtitle {
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  margin: 0 0 20px 0;
  color: #2c3e50;
  background: linear-gradient(to right, #31B310, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.profile-container {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.profile-card {
  background: white;
  border-radius: 15px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 800px;
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading {
  text-align: center;
  padding: 50px 0;
}

.spinner {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #31B310;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.error-message {
  text-align: center;
  padding: 40px 0;
  color: #dc3545;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.error-message p {
  margin-bottom: 20px;
  font-size: 16px;
}

.retry-btn {
  padding: 10px 24px;
  background: linear-gradient(to right, #31B310, #2a990e);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 20px;
  }

  .profile-card {
    padding: 30px 20px;
  }

  .page-subtitle {
    font-size: 1.5rem;
  }
}
</style>
